package cn.tedu.mall.seckill.timer.job;

import cn.tedu.mall.pojo.seckill.model.SeckillSku;
import cn.tedu.mall.pojo.seckill.model.SeckillSpu;
import cn.tedu.mall.seckill.mapper.SeckillSkuMapper;
import cn.tedu.mall.seckill.mapper.SeckillSpuMapper;
import cn.tedu.mall.seckill.utils.SeckillCacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SeckillInitialJob implements Job {
    @Autowired
    private SeckillSpuMapper seckillSpuMapper;

    @Autowired
    private SeckillSkuMapper seckillSkuMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        LocalDateTime time=LocalDateTime.now().plusMinutes(5);
        // 查询5分钟后的秒杀商品(spu)
        List<SeckillSpu> seckillSpus= seckillSpuMapper.findSeckillSpusByTime(time);
        for(SeckillSpu seckillSpu:seckillSpus){
            Long spuId=seckillSpu.getSpuId();
            List<SeckillSku> seckillSkus =seckillSkuMapper.findSeckillSkuBySpuId(spuId);
            for(SeckillSku seckillSku:seckillSkus){
                log.info("开始预热spu对应的多个sku的库存数");
                //以键值对的方式存进redis➡先确定key
                String skuStockKey=SeckillCacheUtils.getStockKey(seckillSku.getSkuId());
                if(redisTemplate.hasKey(skuStockKey)){
                    log.info("{}号sku的库存数已经缓存过了",seckillSku.getSkuId());
                }else{
                   //set(库存数,保存时间即两个小时多点,时间单位)；为方便测试保存时间为5分钟
                    stringRedisTemplate.boundValueOps(skuStockKey)
                            .set(seckillSku.getSeckillStock()+"",1000*60*5+ RandomUtils.nextInt(10000), TimeUnit.MILLISECONDS);
                    log.info("{}号sku的库存数缓存成功~~",seckillSku.getSkuId());
                }

            }
            //随机码的key为提前定好的前缀(常量)+spuId
            String randCodeKey=SeckillCacheUtils.getRandCodeKey(spuId);
            if(redisTemplate.hasKey(randCodeKey)){
                log.info("这个随机码{}已经缓存过了",randCodeKey);
            }else {
                int randCode=RandomUtils.nextInt(90000)+10000;
                redisTemplate.boundValueOps(randCodeKey)
                .set(randCode,1000*60*5+ RandomUtils.nextInt(10000), TimeUnit.MILLISECONDS);
                log.info("随机码缓存成功~");
            }
        }


    }
}
